<template>
  <div>
    <div v-loading="pageLoading">
      <!-- 个人信息 -->
      <modPersonalInfo ref="refModPersonalInfo" :dict="dict.dict" :user-data="userData" class="gl_mb_20" />

      <!-- 中跆协会员 -->
      <modMemberInfo v-if="hasModMemberInfo" ref="refModMemberInfo" :dict="dict.dict" :user-data="userData" class="gl_mb_20" />

      <!-- 中跆协级位段位 -->
      <modTkwChiDan v-if="hasModTkwChiDan" ref="refModTkwChiDan" :dict="dict" :user-data="userData" class="gl_mb_20" />

      <!-- 国际台协段位 -->
      <modTkwIntDan v-if="hasModTkwIntDan" ref="refModTkwIntDan" :dict="dict" :user-data="userData" />
    </div>

    <el-row>
      <el-col class="step_btn" :span="24" align="center">
        <el-button @click="onPrevStep">上一步</el-button>
        <el-button :loading="nextLoading" type="primary" @click="getFormsData">下一步</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import modPersonalInfo from '../components/modPersonalInfo';
import modMemberInfo from '../components/modMemberInfo';
import modTkwChiDan from '../components/modTkwChiDan';
import modTkwIntDan from '../components/modTkwIntDan';

import { CopyData } from '@/lib';
import { SiSTKWEventsManagementRegisterDto } from '@/lib/form/train/swaggerForm.js';

import {
  api_GET_EventsManagementUserUserType, // 获取当前用户注册类型
  api_POST_EventsManagementRegister, // 添加会员
  api_PUT_EventsManagementRegisterId // 更新会员
} from '@/extend/api/gameswaggerApi/app';

import {
  api_POST_TrainTrainningEntryAllowEntry
} from '@/extend/api/trainswaggerApi/app.js';

export default {
  components: {
    modPersonalInfo,
    modMemberInfo,
    modTkwChiDan,
    modTkwIntDan
  },
  props: {
    // 传入的个人信息数据
    userData: {
      type: Object,
      default() {
        return {};
      }
    },
    // 传入的个人信息数据
    trainInfo: {
      type: Object,
      default() {
        return {};
      }
    },
    requiredIdData: {
      type: Object,
      default() {
        return {};
      }
    },
    dict: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data () {
    return {
      vo: new SiSTKWEventsManagementRegisterDto(),
      pageLoading: false, // 页面Loading
      nextLoading: false // 下一页Loading
    };
  },
  computed: {
    // 是否需要中跆协会员信息
    hasModMemberInfo () {
      if (this.trainInfo.id) {
        return this.trainInfo.setting && this.trainInfo.setting.isCTAMemberRequired;
      } else {
        return false;
      }
    },
    // 是否需要中跆协级位段位
    hasModTkwChiDan () {
      if (this.trainInfo.id) {
        return this.trainInfo.setting && this.trainInfo.setting.isCTABeltRequired;
      } else {
        return false;
      }
    },
    // 是否需要国际台协段位
    hasModTkwIntDan () {
      if (this.trainInfo.id) {
        return this.trainInfo.setting && this.trainInfo.setting.isWTABeltRequired;
      } else {
        return false;
      }
    },
    formList () {
      return {
        refModPersonalInfo: true,
        refModMemberInfo: this.hasModMemberInfo,
        refModTkwChiDan: this.hasModTkwChiDan,
        refModTkwIntDan: this.hasModTkwIntDan
      };
    }
  },
  watch: {
    userData: {
      immediate: true,
      deep: true,
      handler(val) {
        if (val.id) {
          // 起始点
          CopyData(this.userData, this.vo);
        }
      }
    }
  },
  methods: {
    // 获取各个表单数据
    getFormsData () {
      const _all = [];
      for (const k in this.formList) {
        const ktem = this.formList[k];
        if (ktem) {
          _all.push(this.$refs[k].getInsideUserData());
        }
      }

      Promise.all(_all)
        .then(
          res => {
            this.pageLoading = true;
            this.nextLoading = true;
            this.mergeFormDataToVO(res);

            if (this.requiredIdData.registerId) {
              this.updatePersonalInfo();
            } else {
              this.createPersonalInfo();
            }
          }
        )
        .catch(
          error => {
            this.pageLoading = false;
            this.nextLoading = false;
            console.log('error: ', error);
            this.$message({
              message: `请先完善必填信息`,
              type: 'warning',
              showClose: true
            });
          }
        );
    },
    // 将数据合并到VO
    mergeFormDataToVO (list) {
      for (let i = 0; i < list.length; i++) {
        const item = list[i];
        CopyData(item, this.vo);
      }

      // 将空字符串数据置为 null 避免传到后端报500
      for (const k in this.vo) {
        const ktem = this.vo[k];
        if (ktem === '') {
          this.vo[k] = null;
        }
      }
    },
    // 更新个人信息
    updatePersonalInfo() {
      this.vo.isCurrentUser = true;
      this.vo.joinCurrentDelegation = false;
      api_PUT_EventsManagementRegisterId(this.requiredIdData.registerId, this.vo)
        .then(
          res => {
            this.$emit('onSetUserInfo', res);
            // 校验是否允许报名
            this.checkAllowEntry();
          },
          error => {
            this.pageLoading = false;
            this.nextLoading = false;
            this.$message({
              type: 'error',
              showClose: true,
              message: `修改用户信息失败 ${error.error.message}`
            });
          }
        );
    },
    // 创建个人信息
    createPersonalInfo() {
      this.vo.isCurrentUser = true;
      this.vo.joinCurrentDelegation = false;
      this.vo.registerTypeCode = 'I';
      // 将空字符串转为Null
      for (const k in this.vo) {
        const ktem = this.vo[k];
        if (ktem === '') {
          this.vo[k] = null;
        }
      }
      api_POST_EventsManagementRegister(this.vo)
        .then(
          res => {
            console.log('createPersonalInfo > api_POST_EventsManagementRegister > res: ', res);
            this.reGetUserType();
          },
          error => {
            this.pageLoading = false;
            this.nextLoading = false;
            this.$message({
              type: 'error',
              showClose: true,
              message: `创建用户信息失败 ${error.error.message}`
            });
          }
        );
    },
    // 重新获取UserType
    reGetUserType() {
      api_GET_EventsManagementUserUserType()
        .then(res => {
          this.$store.dispatch('user/getSaveCurrentUserType', res)
            .then(
              () => {
                // 校验是否允许报名
                this.checkAllowEntry();
              }
            );
          // dispatch 后会触发重新获取用户信息不
        });
    },
    // 是否允许报名
    checkAllowEntry () {
      api_POST_TrainTrainningEntryAllowEntry({
        trainningId: this.trainInfo.id,
        registerId: this.requiredIdData.registerId
      })
        .then(
          res => {
            this.pageLoading = false;
            this.nextLoading = false;

            if (res.allowEntry) {
              this.onNextStep();
            } else {
              this.$message({
                type: 'warning',
                showClose: true,
                message: `${res.message}`
              });
            }
          },
          error => {
            this.pageLoading = false;
            this.nextLoading = false;
            this.$message({
              type: 'error',
              showClose: true,
              message: `${error.error.message}`
            });
          }
        );
    },
    onPrevStep () {
      this.$emit('onPrevStep');
    },
    onNextStep () {
      this.$emit('onNextStep');
    }
  }
};
</script>

<style>
  .box_wrap {
    padding: 30px 20px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0px 10px 36px 0px rgba(0, 0, 0, 0.08);
  }
  .box_wrap_title {
    font-size: 16px;
    font-weight: 500;
    line-height: 22px;
    color: #353434;
    margin-bottom: 20px;
  }
</style>

<style lang="scss" scoped>

</style>
